#! /usr/bin/env python
#coding:UTF-8
import os
import smtplib
import sys
import shutil    # 实现删除非空目录
import time      # 实现暂停
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email import encoders

#定义函数 _sendmail
def _sendmail(smtp_server,port,account,password,str_from,list_to,msg):
    smtp = smtplib.SMTP(smtp_server,port)
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
   # smtp.login(account, password)
    smtp.sendmail(str_from, list_to,msg)
    smtp.close()

# 定义函数 _create_msg
def _create_msg(subject_name,image_dir,str_from,list_to):
    msgRoot = MIMEMultipart('related')
        
# 定义邮件主题
    msgRoot['Subject'] = '%s Report: %s on %s' % (sys.argv[5],item_name,host_name)
        
#定义发件人、收件人
    msgRoot['From'] = str_from
    msgRoot['To'] = ",".join(list_to)
    msgRoot.preamble = 'This is a multi-part message in MIME format.'
    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

# 定义邮件正文内容
    contents = ""
    contents += "<!DOCTYPE html><html><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /><head><title></title></head><body>"


# 添加system logo

    fp = open("%s" % system_logo,'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', "soneparOPS.png")
    msgRoot.attach(msgImage)
    contents += "<img src='cid:soneparOPS.png'>"

  #  contents += "<h3 style='color:#0066ff'>索能达(中国)IT运维平台</h3>"
    contents += "<h4>刚刚在 %s 有告警产生，下图是过去6个小时Zabbix监控数据采集到 %s 情况</h4><br>" % (host_name,item_name) 
    contents += "<table>"

# 获取图片目录下文件名清单，并排序
    image_list = []
    image_list = os.listdir(image_dir)
    image_list.sort(key = str.lower)

# 循环清单并添加为附件
    for f in image_list:

      # contents += "<h5>PictureName %s</h5>" % f

       image_fullpath = "%s/%s" % (image_dir,f) 

       fp = open("%s" % (image_fullpath),'rb')
       msgImage = MIMEImage(fp.read())
       fp.close()

       msgImage.add_header('Content-ID', "<%s>" % f)
       msgRoot.attach(msgImage)

       contents += "<tr><img src='cid:%s'></tr><tr></tr>" %f

# table结束   
    contents += "</table>"
    contents += "<h5>Design by © Roger.LING</h5>"
    contents += "</body></html>"

# 定义邮件格式为HTML,并兼容Android显示中文
    msgText = MIMEText(contents,'html',_charset='utf-8')
    msgAlternative.attach(msgText)
   # msgRoot.attach(msgAlternative)     # 邮件中附加text和html文件,一般不需要
    return msgRoot

# Create the root message and fill in the from, to, and subject headers
def main(str_from,list_to,image_dir):
    msgRoot = _create_msg(image_name,image_dir,str_from,list_to)
            
#定义邮件服务器地址、端口
    _sendmail(smtp_server,port,'','',str_from,list_to,msgRoot.as_string())

# 定义发送邮件信息，发件人，收件人，图片目录
if __name__ == '__main__':
   smtp_server = '10.210.1.227'
   port = 25
   str_from = 'adm_zbx@sonepar.com.cn'
   list_to = [
                "roger.ling@sonepar.com.cn"
             ]
   trigger_id = sys.argv[1]
   item_id = sys.argv[2]
   item_name = sys.argv[3]
   host_name = sys.argv[4]
   image_name =  "itemid-%s.png" % item_id
   image_dir = "/data/graph/trigger-%s" % trigger_id
   system_logo = "/data/graph/soneparOPS.png"
   main(str_from,list_to,image_dir)
   
   time.sleep(5)
   shutil.rmtree(image_dir)

